package alternate;

/**
 * @author wcj
 * @Date 2021/7/22 11:46
 * @Version 1.0
 */
public class ObjectImpl {

    private static final Object obj = new Object();
    private static volatile int count = 1;

    public static void main(String[] args) {

        // 奇数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    if (interrupted) {
                        break;
                    }
                    synchronized (obj) {
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }

                        try {
                            obj.notify();
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "奇数线程").start();

        // 偶数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    if (interrupted) {
                        break;
                    }
                    synchronized (obj) {
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }

                        try {
                            obj.notify();
                            if (count <= 100) {
                                obj.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "偶数线程").start();
    }
}
